package com.javaframe.role.security;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;


/**
 * 
 * The class <code>CurrentUser</code> provides a simple way to access the current user<br><br>
 * It can be used in two ways:
 * 1. web application, when user was logined, you can access CurrentUser.getUser() to get the login information
 * 2. junit test, you can call CurrentUser.setUser(IUserDetail user) to set a user that you want to test as if that user has login
 *  
 * $log$<br><br>
 * @see
 */
public class CurrentUser {
	
	private static IUserDetails currentUser = null;
	
	/**
	 * Get current user which stored in session
	 * You must set a user when using junit test
	 * @return IUserDetails
	 */
	public static IUserDetails getUser(){
		//return currentUser if it isn't null
		//this only occurs when the developer set the current user manually in unit test.
		if (currentUser != null)
        {
            return currentUser;
        }

		//if not in unit test environment, get the current user using acegi
		if ((SecurityContextHolder.getContext() == null)
				|| !(SecurityContextHolder.getContext() instanceof SecurityContext)
				|| (((SecurityContext) SecurityContextHolder.getContext())
						.getAuthentication() == null)) {
			return null;
		}

		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth.getPrincipal() == null) {
            return null;
        }
		
		IUserDetails user = null;
		if (auth.getPrincipal() instanceof IUserDetails) {
			user = (IUserDetails)auth.getPrincipal(); 
		}
		
		return user;
	}
	
	/**
	 * when you run junit test, you can call CurrentUser.setUser(IUserDetail user) to set a user that you want to test as if that user has login
	 * This method should only be called in such situation.
	 * 
	 * @param user
	 */
	public static void setUser(IUserDetails user){
		currentUser = user;
	}
}

